package com.tianji.learning.listener;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;
import static com.tianji.common.constants.MqConstants.Queue.QA_LIKED_TIMES_QUEUE;

@Slf4j
@Component
public class LikedTimesChangeListener {

    @Autowired
    private IInteractionReplyService replyService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QA_LIKED_TIMES_QUEUE,durable = "true"),
            exchange = @Exchange(name = LIKE_RECORD_EXCHANGE,type = ExchangeTypes.TOPIC),
            key = QA_LIKED_TIMES_KEY
    ))
    public void listenLikedTimesChange(List<LikedTimesDTO> likedTimesMsg){
        //1、判断消息是否为空
        if(!ObjectUtil.isAllNotEmpty(likedTimesMsg)){
            log.error("接收到的消息异常，消息：{}",likedTimesMsg);
            return;
        }

        //2、接收到消息开始更新数据库回复表的点赞次数
        log.info("接收到了消息，消息：{}",likedTimesMsg);
        List<InteractionReply> replies = new ArrayList<>(likedTimesMsg.size());
        for (LikedTimesDTO likedTimesDTO : likedTimesMsg) {
            replies.add(new InteractionReply().setId(likedTimesDTO.getBizId()).setLikedTimes(likedTimesDTO.getLikedTimes()));
        }
        replyService.updateBatchById(replies);

    }
}
